package cn.example.freid.listener;

import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.h2.tools.RunScript;

import cn.example.freid.util.PropertiesUtil;

@WebListener
public class ServerStartupListener implements ServletContextListener {

    public ServerStartupListener() {
    }

    public void contextDestroyed(ServletContextEvent arg0)  { 
    }

    public void contextInitialized(ServletContextEvent arg0)  { 
    	
    	Connection connection = null;
    	
		try {
			Class.forName(PropertiesUtil.get("dbdriver")).newInstance();
			connection = DriverManager.getConnection(PropertiesUtil.get("dbURL"), 
					PropertiesUtil.get("username"), PropertiesUtil.get("password"));
			FileReader schemaReader = new FileReader(
					getClass().getClassLoader().getResource("schema.sql").getPath());
			FileReader importReader = new FileReader(
					getClass().getClassLoader().getResource("import-data.sql").getPath());
			RunScript.execute(connection, schemaReader);
			RunScript.execute(connection, importReader);
			
		} catch (SQLException | IOException | InstantiationException | IllegalAccessException 
				| ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
    }
	
}
